package com.wan37.logic.listener.handler;

import com.wan37.logic.component.LogicWorkerHandlerCenter;
import com.wan37.logic.domain.vo.AllRoleVO;
import com.wan37.logic.global.reference.SpringContextHolder;
import com.wan37.logic.handler.server.DestroySceneHandler;
import com.wan37.logic.listener.annotation.EventHandler;
import com.wan37.logic.listener.annotation.Listener;
import com.wan37.logic.listener.event.EventType;
import com.wan37.logic.listener.event.user.UserLoginEvent;
import com.wan37.logic.listener.event.user.UserLogoutEvent;
import com.wan37.logic.service.cache.RoleServiceCache;
import com.wan37.logic.service.cache.SceneServiceCache;
import com.wan37.logic.service.cache.UserServiceCache;

import java.util.Map;

/**
 * @author : luoyong
 * @date : 2020-06-30 20:56
 **/
@Listener
public class SceneListenerHandler {
    private SceneServiceCache sceneServiceCache;
    private RoleServiceCache roleServiceCache;
    private UserServiceCache userServiceCache;
    private LogicWorkerHandlerCenter logicWorkerHandlerCenter;

    public SceneListenerHandler() {
        this.sceneServiceCache = SpringContextHolder.getBean("sceneServiceCache");
        this.roleServiceCache = SpringContextHolder.getBean("roleServiceCache");
        this.userServiceCache = SpringContextHolder.getBean("userServiceCache");
        this.logicWorkerHandlerCenter = SpringContextHolder.getBean("logicWorkerHandlerCenter");
    }

    @EventHandler(value = EventType.LOGIN)
    public void login(UserLoginEvent userLoginEvent) {
        String sceneId = sceneServiceCache.sceneNameToIdMap.get("启始之地");
        sceneServiceCache.getSceneServiceMap().get(sceneId).getUserIdSet().add(userLoginEvent.getUserId());
    }

    @EventHandler(value = EventType.LOGOUT)
    public void logout(UserLogoutEvent userLogoutEvent) {
        String sceneId = userServiceCache.getUserServiceMap().get(userLogoutEvent.getUserId()).getSceneId();
        sceneServiceCache.getSceneServiceMap().get(sceneId).getUserIdSet().remove(userLogoutEvent.getUserId());
        //如果是在临时场景离线，需要触发销毁场景逻辑。
        if (sceneServiceCache.getSceneServiceMap().get(sceneId).getLabel() == 1){
            logicWorkerHandlerCenter.distributeWork(sceneId, new DestroySceneHandler(sceneId));
        }
    }
}
